package com.ts.api.module.channel.controller;

import com.gitee.apanlh.annotation.viewresolver.RequestParamVo;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.common.context.ChannelUserContext;
import com.ts.api.common.redis.ChannelMarketRedisKey;
import com.ts.api.module.channel.entity.po.ChannelMarketPO;
import com.ts.api.module.channel.entity.vo.RespChannelMarketVO;
import com.ts.api.module.channel.service.ChannelMarketService;
import com.ts.api.module.match.market.ChannelMarketMatchFacade;
import com.ts.api.module.match.market.internal.executor.model.MarketExecuteFederateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 渠道贷超控制层
 */
@RestController
@RequestMapping("/channel/market")
public class ChannelMarketController {

    @Autowired
    private ChannelMarketService channelMarketService;
    @Autowired
    private ChannelMarketMatchFacade channelMarketMatchFacade;

    /**
     *  获取贷超列表-需要令牌
     */
    @GetMapping("/list")
    public ResultVO<List<RespChannelMarketVO>> list() {
        List<ChannelMarketPO> listChannelMarketPO = channelMarketMatchFacade.dataExchangeMatch();
        List<RespChannelMarketVO> listVO = CopyUtils.copyList(listChannelMarketPO, RespChannelMarketVO.class);

        //  设置是否联登标识
        IteratorUtils.array(listVO, t -> {
            ChannelMarketPO channelMarketPO = CollUtils.findOne(listChannelMarketPO, source -> source.getId().equals(t.getId()));
            if (ValidParam.isNotEmpty(channelMarketPO.getApiFederateUrl())) {
                t.setHasFederate(true);
            }
        });
        return ResultVO.suc(listVO);
    }

    /**
     *  前置匹配贷超-不需要令牌可以访问(目前只有ip撞库贷超或者直接挂链接的贷超,才使用)
     *
     *  @author Pan
     *  @return ResultVO
     */
    @GetMapping("/pre/list")
    public ResultVO<Object> listPre() {
        List<ChannelMarketPO> listChannelMarketPO = channelMarketMatchFacade.dataExchangeMatch();
        return ResultVO.suc(listChannelMarketPO);
    }

    /**
     *  获取根据贷超排序结果获取单个贷超-不需要令牌可以访问(目前只有ip撞库贷超或者直接挂链接的贷超,才使用)
     */
    @GetMapping("/pre/get/sort")
    public ResultVO<RespChannelMarketVO> getPreMarketBySort() {
        ChannelMarketPO channelMarketPO = channelMarketMatchFacade.dataExchangeMatchOneBySequence();
        RespChannelMarketVO marketVO = CopyUtils.copy(channelMarketPO, RespChannelMarketVO.class);
        return ResultVO.suc(marketVO);
    }

    /**
     *  贷超联登
     *
     *  @author Pan
     *  @return ResultVO
     */
    @PostMapping("/federate")
    public ResultVO<Object> federate(@RequestParamVo RequestVO requestVO) {
        Integer marketId = requestVO.getInt("marketId");
        if (ValidParam.isNull(marketId)) {
            return ResultVO.fail("非法参数");
        }

        //  获取渠道对象
        Long channelId = ChannelContext.getId();
        ChannelMarketPO channelMarketPO = channelMarketService.get(channelId, Long.valueOf(marketId));

        //  联登匹配
        MarketExecuteFederateResult marketExecuteFederateResult = channelMarketMatchFacade.federateMatch(channelMarketPO);
        if (ValidParam.isEmpty(marketExecuteFederateResult.getCallUrl())) {
            return ResultVO.fail("无返回联登记录");
        }
        return ResultVO.suc(marketExecuteFederateResult);
    }

    /**
     *  保存当前该用户已经匹配的贷超
     *
     *  @author Pan
     *  @param  requestVO
     *  @return ResultVO
     */
    @PostMapping("/save/user/market/record")
    public ResultVO<RespChannelMarketVO> saveUserMarketRecord(@RequestParamVo RequestVO requestVO) {
        Integer marketId = requestVO.getInt("marketId");
        if (ValidParam.isNull(marketId)) {
            return ResultVO.fail("非法参数");
        }

        //  获取用户对象
        Long id = ChannelUserContext.getId();
        //  获取渠道对象
        Long channelId = ChannelContext.getId();
        Long marketIdLong = Long.valueOf(marketId);

        //  保存本次匹配到的结果
        String key = StringUtils.format("{}:{}", id, channelId);
        ChannelMarketRedisKey.USER_MARKET_RECORD.setForHours(key, marketIdLong, 24);
        return ResultVO.suc();
    }

    /**
     *  获取当前该用户已经匹配的贷超
     *
     *  @author Pan
     *  @return ResultVO
     */
    @GetMapping("/get/user/market/record")
    public ResultVO<RespChannelMarketVO> getUserMarketRecord() {
        //  获取用户对象
        Long id = ChannelUserContext.getId();
        //  获取渠道对象
        Long channelId = ChannelContext.getId();

        //  保存本次匹配到的结果
        String key = StringUtils.format("{}:{}", id, channelId);
        Long marketIdLong = ChannelMarketRedisKey.USER_MARKET_RECORD.get(key, Long.class);
        if (marketIdLong == null) {
            return ResultVO.fail("无数据");
        }

        //  获取贷超数据
        ChannelMarketPO channelMarketPO = channelMarketService.get(channelId, marketIdLong);
        RespChannelMarketVO marketVO = CopyUtils.copy(channelMarketPO, RespChannelMarketVO.class);

        //  删除匹配结果数据记录
        ChannelMarketRedisKey.USER_MARKET_RECORD.delKey(key);
        return ResultVO.suc(marketVO);
    }
}
